import $ from 'jquery';
import Button from './Button';

export default class FontScaleButton  extends Button{

  _init() {
    this.menu = [{
      name: '150%',
      text: this._t('fontScaleXLarge'),
      param: '5'
    }, {
        name: '125%',
        text: this._t('fontScaleLarge'),
        param: '4'
      }, {
        name: '100%',
        text: this._t('fontScaleNormal'),
        param: '3'
      }, {
        name: '75%',
        text: this._t('fontScaleSmall'),
        param: '2'
      }, {
        name: '50%',
        text: this._t('fontScaleXSmall'),
        param: '1'
      }];
    return FontScaleButton.__super__._init.call(this);
  }

  _activeStatus() {
    let active;
    let endNode;
    let endNodes;
    let startNode;
    let startNodes;
    startNodes = this.editor.selection.startNodes();
    endNodes = this.editor.selection.endNodes();
    startNode = startNodes.filter('span[style*="font-size"]');
    endNode = endNodes.filter('span[style*="font-size"]');
    active = startNodes.length > 0 && endNodes.length > 0 && startNode.is(endNode);
    this.setActive(active);
    return this.active;
  }

  command(param) {
    let $scales;
    let containerNode;
    let range;
    range = this.editor.selection.range();
    if (range.collapsed) {
      return;
    }
    document.execCommand('styleWithCSS', false, true);
    document.execCommand('fontSize', false, param);
    document.execCommand('styleWithCSS', false, false);
    this.editor.selection.reset();
    this.editor.selection.range();
    containerNode = this.editor.selection.containerNode();
    if (containerNode[0].nodeType === Node.TEXT_NODE) {
      $scales = containerNode.closest('span[style*="font-size"]');
    } else {
      $scales = containerNode.find('span[style*="font-size"]');
    }
    $scales.each(((_this => (i, n) => {
      let $span;
      let size;
      $span = $(n);
      size = n.style.fontSize;
      if (/large|x-large|small|x-small/.test(size)) {
        return $span.css('fontSize', _this.sizeMap[size]);
      } else if (size === 'medium') {
        return $span.replaceWith($span.contents());
      }
    }))(this));
    return this.editor.trigger('valuechanged');
  }
}

FontScaleButton.prototype.name = 'fontScale';
FontScaleButton.prototype.icon = 'font';
FontScaleButton.prototype.disableTag = 'pre';
FontScaleButton.prototype.htmlTag = 'span';
FontScaleButton.prototype.sizeMap = {
  'x-large': '1.5em',
  'large': '1.25em',
  'small': '.75em',
  'x-small': '.5em'
};